// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import Fk
import Fk.Pages
import Fk.RoomElement

GraphicsBox {
  id: root

  property var selectedItem: []
  property var ok_options: []
  property var ban_swap: false
  property var cards: []
  property var cards_count: 0
  property var ori_cards_count: 0
  property var ori_cards: []
  property var dragging_card: ""
  property var ori_pos: []
  property var area_pos: []
  property var result: []
  property var exchangging: []
  property var exchanged: []
  property int padding: 25
  
  // 根据卡牌数量计算尺寸（每行4张）
  width: 700
  height: 430
  Item {  
    id:areaItem
    anchors.fill: parent
    anchors.topMargin: 20
    anchors.leftMargin: 20
    anchors.rightMargin: 20
    anchors.bottomMargin: 50
    
    
    Repeater {
      id: areaRepeater
      model: cards_count + 4

      delegate: Rectangle {
        color: "#544732"
        width: 95
        height: 132
        radius: 5
        opacity: 0.7
        
        property var trueWith: parent.width - 224
        property var positions: [
            { // 北
              x: trueWith/2 - width/2 + 224,
              y: 10
            },
            { // 南
              x: trueWith/2 - width/2 + 224,
              y: parent.height - height - 10
            },
            { // 西
              x: 10 + 224,
              y: parent.height/2 - height/2
            },
            { // 东
              x: trueWith - width + 224,
              y: parent.height/2 - height/2 - 10
            },

            {
              x: 0,
              y: 0
            },
            {
              x: 102,
              y: 0
            },
            {
              x: 0,
              y: 136
            },
            {
              x: 102,
              y: 136
            },
        ]
        
        x: {
          let Xpos = index < positions.length ? positions[index].x : 0;
          if (area_pos[index] === undefined){
            area_pos[index] = [];
          }
          area_pos[index].x = Xpos;
          return Xpos;
          }
        y: {
          let Ypos = index < positions.length ? positions[index].y : 0;
          if (area_pos[index] === undefined){
            area_pos[index] = [];
          }
          area_pos[index].y = Ypos;
          return Ypos;
          }

        // 显示位置标签
        Text {
          anchors.top: parent.bottom
          anchors.horizontalCenter: parent.horizontalCenter
          text: {
            if (index < 4) {
              return ["北♦", "南♥", "西♣", "东♠"][index]
            } else {
              return ""
            }
          }
          font.pixelSize: 18
          font.family: fontLibian.name
          color: "#ffffff"
        }
      }
    }

    Item{
      id: cardPlace
      anchors.fill: parent
    
      Repeater {
        id: cardRepeater
        model: cards
        delegate: CardItem {
          Component.onCompleted: {
            setData(modelData);
            result[index + 4] =  this;
          }
          autoBack: false
          showDetail: true
          selectable: true
          draggable: true
          property var sourceRepeater: cardRepeater
          property var idx: index + 4
          onDraggingChanged: {
            if (!dragging) return;
            dragging_card = this;
            let i, card
            for (i = 0; i < cardRepeater.count; i++) {
              card = cardRepeater.itemAt(i);
              if (card !== this){
                card.draggable = false;}
            }
          }
          onReleased: updateCardReleased(this, index);
          onXChanged: updateCardDragging(this, index);
          onYChanged: updateCardDragging(this, index);

          property var _trueWith: parent.width - 224
          property var c_positions:[
            {
              x: 0,
              y: 0
            },
            {
              x: 102,
              y: 0
            },
            {
              x: 0,
              y: 136
            },
            {
              x: 102,
              y: 136
            },
          ]
          x: index < c_positions.length ? c_positions[index].x : 0
          y: index < c_positions.length ? c_positions[index].y : 0
          origX: index < c_positions.length ? c_positions[index].x : 0
          origY: index < c_positions.length ? c_positions[index].y : 0
        }
      }

      Repeater {
        id: oriCardRepeater
        model: ori_cards
        delegate: CardItem {
          Component.onCompleted: {
            setData(modelData);
            result[index] =  this;
          }
          autoBack: false
          showDetail: true
          selectable: true
          draggable: true
          property var sourceRepeater: oriCardRepeater
          property var idx: index
          onDraggingChanged: {
            if (!dragging) return;
            dragging_card = this;
            let i, card
            for (i = 0; i < cardRepeater.count; i++) {
              card = cardRepeater.itemAt(i);
              if (card !== this){
                card.draggable = false;}
            }
          }
          onReleased: updateCardReleased(this, index);
          onXChanged: updateCardDragging(this, index);
          onYChanged: updateCardDragging(this, index);

          property var _trueWith: parent.width - 224
          property var _positions: [
            { // 北
              x: _trueWith/2 - width/2 + 224,
              y: 10
            },
            { // 南
              x: _trueWith/2 - width/2 + 224,
              y: parent.height - height - 10
            },
            { // 西
              x: 10 + 224,
              y: parent.height/2 - height/2
            },
            { // 东
              x: _trueWith - width + 224,
              y: parent.height/2 - height/2 - 10
            },
          ]

          x: index < _positions.length ? _positions[index].x : 0
          y: index < _positions.length ? _positions[index].y : 0
          origX: index < _positions.length ? _positions[index].x : 0
          origY: index < _positions.length ? _positions[index].y : 0
        }
      }
    }
    Item {
      id: remindArea
      height: {
        if (cards_count > 2){
          return 272
        } else {
          return 136
        }
      }
      width: {
        if (cards_count > 1){
          return 204
        } else {
          return 102
        }
      }
      Text {
        anchors.top: parent.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        text: "待选卡牌"
        font.pixelSize: 18
        font.family: fontLibian.name
        color: "#ffffff"
      }
    }
    
  }

  //OKbutton
  Item {
    id: buttonArea
    anchors.bottom: root.bottom
    anchors.horizontalCenter: root.horizontalCenter
    height: 40
    width: 100

    MetroButton {
      id: ok_button
      anchors.horizontalCenter: parent.horizontalCenter
      text: luatr("OK")
      enabled: false

      onClicked: {
        close();
        roomScene.state = "notactive";
        let ids = [], i;
        for (i = 0; i < 8; i++){
          if (result[i] === undefined) {
            continue;
          } else {
            ids.push(result[i].cid);
          }
        }        
        const reply = JSON.stringify(
          {
            cardMap: ids
          }
        );
        ClientInstance.replyToServer("", reply);
      }
    }
  }

  Item{
    id: titleArea
    height: 32
    width: 100
    anchors.top: root.top
    anchors.horizontalCenter: root.horizontalCenter

    Text {
      anchors.horizontalCenter: parent.horizontalCenter
      y: 5
      text: "四相"
      font.pixelSize: 30
      font.family: fontLibian.name
      color: "#E4D5A0"
      font.weight: Font.Medium
    }
  }

  function updateCardDragging(_card, n) {
    if (!_card.dragging) return;
    _card.goBackAnim.stop();
    let i, card
    for (i = 0; i < cardRepeater.count; i++) {
      card = cardRepeater.itemAt(i);
      if (!canSwap(_card, card)) {
        card.opacity = 0.5; //变暗
      }
    }
    for (i = 0; i < oriCardRepeater.count; i++) {
      card = oriCardRepeater.itemAt(i);
      if (!canSwap(_card, card)) {
        card.opacity = 0.5; //变暗
      }
    }
    arrageCards(_card, n);
  }

  function updateCardReleased(_card, n) {
    let i, card
    for (i = 0; i < cardRepeater.count; i++) {
      card = cardRepeater.itemAt(i);
      card.draggable = true;
      card.opacity = 1; //复原待选
    }
    for (i = 0; i < oriCardRepeater.count; i++) {
      card = oriCardRepeater.itemAt(i);
      card.draggable = true;
      card.opacity = 1; //复原待选
    }
    if ((exchangging.length > 0) && ban_swap){
      let list = exchangging;
      if (exchanged[_card.idx] === undefined){
        let from = list[0][0].idx;
        let to = list[0][1].idx;
        exchanged[from] = to;
        exchanged[to] = from;
      } else {
        exchanged[exchanged[_card.idx]] = undefined;
        exchanged[_card.idx] = undefined;
      }
    }
    exchangging = []
    _card.goBack(false)
    checkIsOk()
  }

  function arrageCards(_card, n) {
    let i, j, area
    const border = 30
    let ifInside = false
    for (i = 0; i < area_pos.length; i++) {
      area = area_pos[i];
      const areaX = area.x, areaY = area.y;
      if ((_card.x <= areaX + border) && (_card.x >= areaX - border) && (_card.y <= areaY + border) && (_card.y >= areaY - border)) {
        if (result[i] === undefined) {
          [_card.origX, _card.origY] = [areaX, areaY];
          if (result.indexOf(_card) !== -1) {
            j = result.indexOf(_card);
            result[j] = undefined;
          }
          result[i] = _card
        } else if ((result[i] !== _card) && canSwap(_card, result[i])) {
          [_card.origX, result[i].origX] = [result[i].origX, _card.origX];
          [_card.origY, result[i].origY] = [result[i].origY, _card.origY];
          result[i].goBack(true);
          if (result.indexOf(_card) !== -1) {
            j = result.indexOf(_card);
            exchangging = [[_card, result[i]], [j, i]];
            [result[j], result[i]] = [result[i], result[j]];
          } else {
            result[i] = _card;
          }
        }
        ifInside = true;
      }
    }
    if ((exchangging.length > 0) && (!ifInside)) {
      if (exchangging[0][0].dragging) {
        let from = exchangging[0][0], to = exchangging[0][1];
        const i = exchangging[1][0], j = exchangging[1][1];
        [from.origX, to.origX] = [to.origX, from.origX];
        [from.origY, to.origY] = [to.origY, from.origY];
        to.goBack(true);
        [result[j], result[i]] = [result[i], result[j]];
        exchangging = [];
      }
    }
    checkIsOk()
  }

  function canSwap(_card, __card) {
    if (ban_swap){
      if (_card === __card) return true;
      if (_card.sourceRepeater === __card.sourceRepeater) {
        return false
      }
      if (exchanged[_card.idx] !== undefined){
        return exchanged[_card.idx] === __card.idx;
      }
      if (exchanged[__card.idx] !== undefined){
        return exchanged[__card.idx] === _card.idx
      }
    }
    return true
  }

  function checkIsOk() {
    if (result.length < 4) {
      ok_button.enabled = false
      return false
    };
    let i
    for (i = 0; i < 4; i++){
      if (result[i] === undefined){
        ok_button.enabled = false
        return false
      }
    }
    ok_button.enabled = true
    return true
  }

  function loadData(data) {
    var d = data;
    cards = d.cards.map(cid => {
      cards_count++;
      if (typeof cid === 'object') {
        return cid;
      }
      return lcall("GetCardData", cid);
    });
    ori_cards = d.ori_cards.map(cid => {
      ori_cards_count++;
      if (typeof cid === 'object') {
        return cid;
      }
      return lcall("GetCardData", cid);
    });
    ok_options = d.ok_option;
    ban_swap = d.ban_swap;
    checkIsOk()
  }
}
